/*
 * @Description: 描述信息
 * @Version: 版本号
 * @Author: xuebao
 * @Date: 2023-12-14 19:38:51
 * @LastEditors: xuebao
 * @LastEditTime: 2023-12-15 12:12:31
 */
import { IAuthLoader } from '@/router/AuthLoader'
import { searchRoute } from '@/utils'
import { Tabs } from 'antd'
import { useEffect, useState } from 'react'
import { useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
interface TabsItem {
  key: string
  label: string
  closable: boolean
}
export default function TabsFc() {
  const { pathname } = useLocation()
  const [activeKey, setActiveKey] = useState('')
  const [tabsList, setTabsList] = useState<TabsItem[]>([{ key: '/welcome', label: '首页', closable: false }])
  const data = useRouteLoaderData('layout') as IAuthLoader
  const navigate = useNavigate()
  useEffect(() => {
    addTags()
  }, [pathname])
  //创建页签
  const addTags = () => {
    const route = searchRoute(pathname, data.menuList)
    if (!route) return
    //去重
    if (!tabsList.find((item) => item.key === pathname)) {
      tabsList.push({
        key: route.path,
        label: route.menuName,
        closable: pathname !== '/welcome',
      })
    }

    setTabsList([...tabsList])
    setActiveKey(pathname)
  }
  //路由切换
  const handleChange = (path: string) => {
    navigate(path)
  }
  //删除
  const handleDel = (path: string) => {
    if (pathname === path) {
      tabsList.forEach((item, index) => {
        if (item.key !== pathname) return
        const nextTab = tabsList[index + 1] || tabsList[index - 1]
        if (!nextTab) return
        navigate(nextTab.key) //跳转到下一个页面
      })
    }
    setTabsList(tabsList.filter((item) => item.key !== path))
  }

  return (
    <Tabs
      items={tabsList}
      activeKey={activeKey}
      tabBarStyle={{ height: 40, marginBottom: 10, backgroundColor: 'var(--bg-color)' }}
      hideAdd
      type='editable-card'
      onChange={handleChange}
      onEdit={(path) => handleDel(path as string)}
    />
  )
}
